<template>
  <div class="question-type-three">
    <div class="question-header">
      <div class="question-progress">
        <span>
          Question
          <i>{{ questionNumber }}</i>
          /{{ totalQuestions }} (Group {{ stageNumber }}/5)
        </span>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: `${progress}%` }"></div>
        </div>
      </div>
    </div>

    <h2 class="question-title">Would you rather?</h2>

    <div class="options-container">
      <div class="divider-text" :class="{ 'hide-divider': selectedOption !== null }">OR</div>
      <!-- 选项1 -->
      <div
        class="option-item option-top"
        :class="{
          selected: selectedOption === question.answers[0].id,
          'not-selected': selectedOption === question.answers[1].id,
          'higher-percent': selectedOption !== null && animatedPercentages[0] >= animatedPercentages[1],
          locked: isSelectionLocked && selectedOption !== question.answers[0].id,
          animating: isAnimating,
        }"
        @click="selectOption(question.answers[0].id, question.id)"
      >
        <div class="option-content">
          <div class="option-text">{{ question.answers[0].answer }}</div>
          <div class="option-percentage" v-if="selectedOption !== null">
            <!-- 对小数点后的数字进行四舍五入，保留 0 位小数 -->
            <div class="percentage-value">{{ animatedPercentages[0].toFixed(0) }}%</div>
          </div>
        </div>
      </div>

      <!-- 选项2 -->
      <div
        class="option-item option-bottom"
        :class="{
          selected: selectedOption === question.answers[1].id,
          'not-selected': selectedOption === question.answers[0].id,
          'higher-percent': selectedOption !== null && animatedPercentages[1] > animatedPercentages[0],
          locked: isSelectionLocked && selectedOption !== question.answers[1].id,
          animating: isAnimating,
        }"
        @click="selectOption(question.answers[1].id, question.id)"
      >
        <div class="option-content">
          <div class="option-text">{{ question.answers[1].answer }}</div>
          <div class="option-percentage" v-if="selectedOption !== null">
            <div class="percentage-value">{{ animatedPercentages[1].toFixed(0) }}%</div>
          </div>
        </div>
      </div>
    </div>

    <div class="navigation-buttons">
      <button class="prev-btn" @click="handlePrevQuestion" :disabled="questionNumber === 1 && stageNumber === 1">Previous question</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'QuestionTypeThree',
  props: {
    question: {
      type: Object,
      required: true,
    },
    questionNumber: {
      type: Number,
      required: true,
    },
    totalQuestions: {
      type: Number,
      required: true,
    },
    stageNumber: {
      type: Number,
      required: true,
    },
    progress: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      selectedOption: null,
      animatedPercentages: [0, 0],
      animationInterval: null,
      isSelectionLocked: false,
      isAnimating: false,
    }
  },
  methods: {
    selectOption(optionId, qId) {
      // 如果选项已锁定，不允许再次点击
      if (this.isSelectionLocked) {
        console.log('选项已锁定，无法再次选择')
        return
      }

      // 设置动画标志和锁定标志
      this.isAnimating = true
      this.isSelectionLocked = true

      // 清除之前的动画定时器
      if (this.animationInterval) {
        clearInterval(this.animationInterval)
        this.animationInterval = null
      }

      // 初始化百分比为0
      this.animatedPercentages = [0, 0]
      this.selectedOption = optionId

      // 获取目标百分比数据
      // 如果question.answers包含probability字段，使用该值
      // 否则使用默认值[50, 50]
      const targetPercentages = [this.question.answers[0].probability || 50, this.question.answers[1].probability || 50]

      // 开始百分比动画
      this.startPercentageAnimation(targetPercentages)

      // 触发选择事件
      this.$emit('select-option', optionId, qId)
    },

    startPercentageAnimation(targetPercentages) {
      if (this.animationInterval) clearInterval(this.animationInterval)

      const duration = 800
      const steps = 60
      const stepDuration = duration / steps
      let currentStep = 0

      const increments = [targetPercentages[0] / steps, targetPercentages[1] / steps]

      this.animationInterval = setInterval(() => {
        currentStep++

        this.animatedPercentages = [Math.min(increments[0] * currentStep, targetPercentages[0]), Math.min(increments[1] * currentStep, targetPercentages[1])]

        if (currentStep >= steps) {
          clearInterval(this.animationInterval)
          this.animationInterval = null
          this.animatedPercentages = [...targetPercentages]

          // 动画结束，清除动画标志
          this.isAnimating = false

          // 动画完成后跳转到下一题
          setTimeout(() => {
            this.$emit('next-question')
          }, 500)
        }
      }, stepDuration)
    },

    checkPreviousAnswer() {
      const answers = this.$store.state.answers || []

      // 查找当前阶段和问题的历史答案
      const previousAnswer = answers.find((answer) => answer.stageId === this.stageNumber && answer.questionId === this.questionNumber - 1)

      if (previousAnswer !== undefined) {
        // 设置选中的选项ID
        this.selectedOption = previousAnswer.selectedOption

        // 获取目标百分比
        const targetPercentages = [this.question.answers[0].probability || 50, this.question.answers[1].probability || 50]

        // 直接设置百分比值，不进行动画
        this.animatedPercentages = [...targetPercentages]
      }
    },

    handlePrevQuestion() {
      // console.log('QuestionTypeThree 组件中的 handlePrevQuestion 被触发')
      // console.log('当前阶段:', this.stageNumber, '当前题号:', this.questionNumber)

      this.$emit('prev-question')
    },
  },
  created() {
    this.checkPreviousAnswer()
    this.isSelectionLocked = false
  },
  beforeDestroy() {
    if (this.animationInterval) {
      clearInterval(this.animationInterval)
    }
  },
}
</script>

<style scoped lang="scss">
.question-type-three {
  max-width: 500px;
  margin: 0 auto;
   padding: 70px 16px 16px;
  min-height: 100vh;
  // background: #f5f5fd;
  display: flex;
  flex-direction: column;
}

.question-header {
 width: 100%;
  padding: 16px;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100;
  background-color: #e2e4f5;
}

.question-progress {
  font-size: 14px;
  color: #111;
  > span {
    display: block;
    width: 100%;
    text-align: left;
    font-size: 14px;
    > i {
      color: #775ae0;
      font-size: 18px;
      font-family: NotoSans-SemiBold;
    }
  }
}

.progress-bar {
  height: 5px;
  background: #fff;
  border-radius: 10px;
  margin-top: 8px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #775ae0 0%, #f78295 100%);
  border-radius: 10px;
  transition: width 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

.question-title {
  font-size: 18px;
  margin-bottom: 12px;
  text-align: center;
  font-family: NotoSans-SemiBold;
}

.options-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 24px;
  position: relative;
  flex-grow: 1;
  height: 70vh;
}

.divider-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: opacity 0.3s ease;
  font-family: NotoSans-SemiBold;
}

.hide-divider {
  opacity: 0;
}

.option-item {
  border-radius: 15px;
  padding: 30px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: 100px;
  color: white;
  font-weight: 500;
  text-align: center;
  transition: all 0.8s cubic-bezier(0.19, 1, 0.22, 1);
  position: relative;
  overflow: hidden;
  flex-grow: 1;
  height: 50%;
}

/* 被锁定的选项 */
.option-item.locked {
  cursor: not-allowed;
  opacity: 0.7;
}

.option-top {
  background-color: #f05b56; /* 红色 */
}

.option-bottom {
  background-color: #3367d6; /* 蓝色 */
}

.option-item.selected {
  transform: scale(1.03);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  z-index: 5;
}

.option-item.not-selected {
  opacity: 0.5;
  filter: grayscale(0.8);
}

/* 固定增加10%高度给百分比更高的选项 */
.option-item.higher-percent {
  height: 55%;
}

.option-item:not(.higher-percent) {
  height: 45%;
}

.option-content {
  position: relative;
  z-index: 2;
}

.option-text {
  font-size: 18px;
  line-height: 1.4;
  margin-bottom: 5px;
  font-family: NotoSans-SemiBold;
}

.option-percentage {
  margin-top: 15px;
}

.percentage-value {
  font-size: 48px; /* 增大字体大小 */
  font-weight: bold;
  margin-bottom: 5px;
  font-family: NotoSerif-ExtraBold;
}

.navigation-buttons {
  // margin-top: auto;
  display: flex;
  justify-content: space-between;
}

.prev-btn {
  background: #775ae0;
  color: white;
  border: none;
  padding: 14px 20px;
  border-radius: 24px;
  font-size: 18px;
  // cursor: pointer;
  width: 100%;
  transition: background 0.2s;
  font-family: NotoSans-SemiBold;
}

.prev-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.prev-btn:hover:not(:disabled) {
  background: #7a6ba6;
}
</style>
